package com.katydid;

import java.util.List;
import java.util.logging.Logger;

import javax.ejb.Local;
import javax.ejb.LocalBean;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.katydid.domain.Category;
import com.katydid.domain.Note;
import com.katydid.domain.Tag;
import com.katydid.util.LogInterceptor;
import com.katydid.util.Loggable;


/**
 * Session Bean implementation class NoteManager
 */
@Loggable
@Stateless
@Local(NoteManager.class)
@Remote(NoteManagerRemote.class)
@LocalBean
@Interceptors(LogInterceptor.class)
public class NoteManagerImpl implements NoteManager {    // with @local, @Remote, doesn't require to implement intefaces

	//@Inject
	@PersistenceContext(unitName = "Note")
	private EntityManager em;
	
	@Inject
	private transient Logger logger;
	
    /**
     * Default constructor. 
     */
    public NoteManagerImpl() {
        // TODO Auto-generated constructor stub
    }    
    
    public void addCategory(Category cat) {
    	em.persist(cat);
    }
    
    public void updateCategory(Category cat) {
    	logger.info("category " + cat.getId() + " is updated.");
    	em.merge(cat);
    }
    
    public void removeCategory(Category cat) {
    	em.remove(em.merge(cat));
    }
    
    public List<Category> getAllCategories() {
    	Query query = em.createNamedQuery(Category.FIND_ALL);
		return query.getResultList();
    }
    
    public Category getCategory(long catId) {
    	return em.find(Category.class, catId);
    }
    
    public void addTag(Tag tag) {
    	em.persist(tag);
    }

    public void updateTag(Tag tag) {
    	em.merge(tag);
    }
    
    public void removeTag(Tag tag) {
    	em.remove(em.merge(tag));
    }
    
    public void addNote(Note note) {
    	em.persist(note);
    }

    public void updateNote(Note note) {
    	em.merge(note);
    }
    
    public void removeTag(Note note) {
    	em.remove(em.merge(note));
    }
}
